<template>
    
  </template>
  <script setup lang="ts">
  import { ref, reactive, nextTick, toRef } from "vue";
  import baseService from "@/service/baseService";
  import { ElMessage, ElMessageBox } from "element-plus";
  import { timestampToDayHM, timestampToHM, timestampToDate, formatAmount } from "@/utils/utils"
  import { regionData, codeToText, TextToCode } from 'element-china-area-data'
  import { fileUploader } from '@/utils/upload.js'
  import { useRouter, useRoute } from 'vue-router';
  
  import { EluiChinaAreaDht } from 'elui-china-area-dht'
  const chinaData = new EluiChinaAreaDht.ChinaArea().chinaAreaflat

  const router = useRouter();
  const route = useRoute();
  // 查询参数
  const queryForm = reactive({
    kw: '',
    pageNo: 1,
    pageSize: 10
  });
  // 列表内容数量
  const total = ref(0);
  // 列表是否加载
  const loading = ref(true);
  // 列表返回值
  const list = ref<any[]>([]);
  const selectedCityOptions = ref<any[]>([]);
  const categoryList = ref<any[]>([]);
  
  // 表单实例
  const formRef = ref();
  // 是否打开弹出框
  const open = ref(false);
  const isEdit = ref(0);
  const openDetail = ref(false);
  // 弹出框标题
  const title = ref('');
  const detailData = ref();
  // 提交表单数据
  let editForm = toRef(
    reactive({
      productId: '',
      name: '',
      tags: '',
      pics: '',
      mainPic: '',
      status: 1,
      quantity: '',
      describ: '',
      viewCount: 0,
      saleCount: 0,
      subTitle: '',
      price: '',
    })
  );
  const options = ref(regionData)
  const selectedOptions = ref<any>([])
  //多图上传的返回图片url数组
  const pics = ref<any>([])
  const uploadUrlPath = ref();

  // 表单验证
  const rules = ref({
    deptName: [{ required: true, message: "规则名称不能为空", trigger: "blur" }],
    leader: [{ required: true, message: "负责人不能为空", trigger: "blur" }],
    phone: [{ required: true, message: "手机号不能为空", trigger: "blur" }],
    email: [{ required: true, message: "邮箱不能为空", trigger: "blur" }]
  });
  
  /**
   * 查询列表
   */
  const getList = () => {
    loading.value = true;
    baseService
      .post("/admin/product/list", queryForm).then((res) => {
        loading.value = false;
        if (res.code === 200) {
          list.value = res.data.records;
          total.value = res.data.totalrecord;
        } else {
          list.value = [];
        }
      })
      .catch(() => {
        loading.value = false;
      });
  };
  
  /**
   * 搜索按钮操作
   */
  function handleQuery() {
    queryForm.pageNo = 1;
    getList();
  }
  
  /**
   * 表单重置
   */
  function reset() {
    editForm.value = {
      productId: '',
      name: '',
      tags: '',
      pics: '',
      mainPic: '',
      status: 1,
      quantity: '',
      describ: '',
      viewCount: 0,
      saleCount: 0,
      subTitle: '',
      price: '',
    };
    selectedCityOptions.value = []
    pics.value = []
  
    nextTick(() => {
      formRef.value?.resetFields();
    });
  }
  
  /**
   * 新增按钮操作
   */
  function handleAdd() {
    reset();
    open.value = true;
    isEdit.value = 0;
    console.log('图片:',pics.value)
    title.value = "添加";
  }

  function showDetail(data: any){
    console.log('进入详情页:', data)
    router.push({path:'/admin/goods/detail', query: {pid:data}})
  }
  
  /**
   * 修改按钮操作
   * @param id 主键
   */
  function handleUpdate(id: string) {
    open.value = true;
    title.value = "修改";
    isEdit.value = 1;
    reset();
    baseService.get(`/admin/product/info/${id}`).then((res) => {
      if (res.code === 200) {
        editForm.value = res.data;
        pics.value = res.data.pics.split(',')
      }
    });
  }

  /**
   * 设为推荐
   * @param id 
   */
   function handleRec(id: string, htype: number) {
    title.value = "修改";
    reset();
    let req = {
      id: id,
      type: htype
    }
    baseService.post(`/admin/product/set/rec`, req).then((res) => {
      if (res.code === 200) {
        ElMessage.success("设置成功");
      }
    });
  }
  
  /**
   * 提交按钮
   */
  function submitForm() {
    formRef.value.validate((valid: boolean) => {
      if (!valid) return;
      console.log('图片字段', pics.value)
      editForm.value.pics = pics.value.join(',')
      baseService.post(`/admin/product/save`, editForm.value).then((res) => {
        if (res.code === 200) {
          ElMessage.success(res.msg);
          open.value = false;
          getList();
        } else {
          ElMessage.error(res.msg);
        }
      });
    });
  }
  
  /**
   * 删除按钮操作
   * @param id 主键
   */
  function handleDelete(id: any, optType: number) {
    let msg = '确认要下架该商品吗?'
    if(optType == 1){
      msg = '确定要重新上架吗？'
    }
    ElMessageBox.confirm(msg, "提示").then(() => {
      baseService.get(`/admin/product/delete/${id}/${optType}`).then((res) => {
        if (res.code === 200) {
          ElMessage.success(res.msg);
          getList();
        } else {
          ElMessage.error(res.msg);
        }
      });
    });
  }

  /**
   * 更新状态
   * @param id 
   */
  function handleStatus(id: any, status: any) {
    let msg = '确定要将门店更新为营业状态吗？'
    if(status == -1){
      msg = '确定将门店更新为关店状态吗？'
    }
    ElMessageBox.confirm(msg, "提示").then(() => {
      baseService.delete(`/manager/update/status`, {productId: id, status: status}).then((res) => {
        if (res.code === 200) {
          ElMessage.success(res.msg);
          getList();
        } else {
          ElMessage.error(res.msg);
        }
      });
    });
  }

  function handlePreview(file: any) {
      console.log(file);
  }
  function handleRemove(file: any, fileList: any) {
    alert('移除')
      //return this.$confirm(`确定移除 ${file.name}？`);
  }
  function beforeRemove(file: any, fileList: any) {
    alert('移除')
      // return this.$confirm(`确定移除 ${file.name}？`);
  }

    // 图片上传
  function uploadSectionFile(file: any) {
    console.log('选定图片！',file)
    const typeArr = ["image/png", "image/gif", "image/jpeg", "image/jpg"];
    const isJPG = typeArr.indexOf(file.raw.type) !== -1;
    const isLt3M = file.size / 1024 / 1024 < 3;
    if (!isJPG) {
      // ElMessage.error("只能是图片!");
      // this.$refs.upload.clearFiles();
      // this.files = null;
      return;
    }
    if (!isLt3M) {
      // ElMessage.error("上传图片大小不能超过 3MB!");
      // this.$refs.upload.clearFiles();
      // this.files = null;
      return;
    }
    // FormData 对象
    var formData = new FormData();
    // 文件对象
    formData.append("myFile", file.raw)
    console.log('上传图片表单：', formData)
    fileUploader(formData).then((res) => {
      if (res.data.errno==0) {
        //this.photoObj = res.data.data.objectId;
        console.log('图片上传成功！', res.data)
        pics.value.push(res.data.data);
      } else {
        // ElMessage.error(res.data.message);
      }
    })
  }
    // 上传LOGO图片
  function uploadLogoFile(file: any){
    const typeArr = ["image/png", "image/gif", "image/jpeg", "image/jpg"];
    const isJPG = typeArr.indexOf(file.raw.type) !== -1;
    const isLt3M = file.size / 1024 / 1024 < 3;
    if (!isJPG) {
      // ElMessage.error("只能是图片!");
      // this.$refs.upload.clearFiles();
      // this.files = null;
      return;
    }
    if (!isLt3M) {
      // ElMessage.error("上传图片大小不能超过 3MB!");
      // this.$refs.upload.clearFiles();
      // this.files = null;
      return;
    }
    var formData = new FormData();
    formData.append("myFile", file.raw)
    fileUploader(formData).then((res) => {
      console.log('LOGO上传成功', res)
      if (res.data.errno==0) {
        editForm.value.mainPic=res.data.data[0]
      } else {
        // ElMessage.error(res.data.message);
      }
    })
  }
  // 移除LOGO图片
  function handleRemoveLogo(file: any){
    editForm.value.mainPic=''
    console.log('移除LOGO图片！',editForm.value.mainPic)
  }

  // 移除多图中的其中一张
  function handleRemovePics(idx: number){
    console.log('移除图片下标为：', idx)
    pics.value.splice(idx, 1);
  }
  
  // 富文本编辑器：上传图片成功
  function uploadEditorSuccess(res: any, file:any) {
    // console.log("上传成功")
    // // this.$emit('upload',res, file)
    // console.log(res, file);
    // //拼接出上传的图片在服务器的完整地址
    // let imgUrl=res.data[0];
    // let type=imgUrl.substring(imgUrl.lastIndexOf(".")+1);
    // console.log(type);
    // // 获取富文本组件实例
    // let quill = this.$refs.customQuillEditor.quill;
    // // 获取光标所在位置
    // let length = quill.getSelection().index;
    // // 插入图片 res.info为服务器返回的图片地址
    // quill.insertEmbed(length, 'image', imgUrl)
    // // 调整光标到最后
    // quill.setSelection(length + 1)
    // //取消上传动画
    // this.quillUpdateImg = false;
  }
  // 上传(文件)图片失败
  function uploadEditorError(res: any, file: any) {
    console.log(res);
    console.log(file);
    //页面提示
    ElMessage.error('上传图片失败')
    //取消上传动画
    // this.quillUpdateImg = false;
  }
  //上传图片之前async
  function beforeEditorUpload(res: any, file: any){
    //显示上传动画
    // this.quillUpdateImg = true;
    console.log(res);
  }
  //上传组件返回的结果
  function uploadResult (res: any){
    uploadUrlPath.value=res;
  }
  
  getList();
  </script>
  
<style scoped>
.price{
color: #F56C6C;
font-weight: bold;
}
.pointer{
    cursor: pointer;
}
.pointer:HOVER{
    color: #409eff;
}
.introduction{
  width: 80%;
  margin: 15px auto;
  white-space: pre-line;
}
.addpic{
  font-size: 22px;
  padding: 20px 25px 15px 25px;
  border: 2px dashed #ccc;
  color: #888;
  height: 68px;
}
.img-list{
  display: flex;
  flex-wrap: wrap;
}
.img-list .img-li{
  width: 260px;
  position: relative;
  margin-right: 10px;
}
.logo-remove{
  font-size: 22px;
  position: absolute;
  top: 10px;
  right: 10px;
  color: #f00;
  cursor: pointer;
  text-shadow: #000 4px 4px 5px;
}
.logo-remove .el-icon{
  box-shadow: #fff 3px 5px 6px;
  background-color: #fff;
}
.logo-remove:HOVER{
  color: #F56C6C;
}
</style>
  